import { ACCESS_TOKEN, LOGIN } from "@/store/mutation-types";
import { login } from "@/api/api";
import router from "@/router";

export default {
  namespaced: true,
  state: {
    login: false,
    has_token: false,
    token: "",
    userId: ""
  },
  getters: {},
  mutations: {
    [ACCESS_TOKEN](state, data) {
      state.has_token = data;
    },
    [LOGIN](state, data) {
      localStorage.setItem("token", data.newToken);
      localStorage.setItem("userId", data.data.userId);
      state.token = data.newToken;
      state.userId = data.data.userId;
      state.login = true;
      router.push("/index");
    }
  },
  actions: {
    logout({ commit }) {
      commit(LOGIN, false);
    },
    async login({ commit }, data) {
      let acc = await login(data);
      commit(LOGIN, acc);
    }
  }
};
